package com.xtianzhuang.www.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.xtianzhuang.www.dao.TdCityMapper;
import com.xtianzhuang.www.dao.TdFileMapper;
import com.xtianzhuang.www.dao.TfUMarriageMapper;
import com.xtianzhuang.www.entity.TdCityExample;
import com.xtianzhuang.www.entity.TdFile;
import com.xtianzhuang.www.entity.TfUMarriage;
import com.xtianzhuang.www.entity.TfUMarriageExample;
import com.xtianzhuang.www.entity.constants.IsDeletedConstants;
import com.xtianzhuang.www.entity.request.DeletePersonRequest;
import com.xtianzhuang.www.entity.request.SavePersonRequest;
import com.xtianzhuang.www.service.BlindDateService;
import com.xtianzhuang.www.service.base.BaseServiceBiz;

@Service("blindDateServiceBiz")
@Transactional(rollbackFor = Exception.class)
public class BlindDateServiceBiz extends BaseServiceBiz implements BlindDateService {
	@Autowired
	private TfUMarriageMapper tfUMarriageMapper;
	@Autowired
	TdFileMapper tdFileMapper;
	@Autowired
	TdCityMapper tdCityMapper;
	@Override
	public void savePerson(HttpServletRequest request, SavePersonRequest savePersonRequest) throws Exception {
		// TODO Auto-generated method stub
		if (checkData(request, savePersonRequest)) {
			addTfUMarrage(request, savePersonRequest);
		}

	}

	public void addTfUMarrage(HttpServletRequest request, SavePersonRequest savePersonRequest) {
		TfUMarriage tfUMarriage = new TfUMarriage();
		tfUMarriage.setUserName(savePersonRequest.getUserName());
		tfUMarriage.setAge(savePersonRequest.getAge());
		tfUMarriage.setAnotherRequest(savePersonRequest.getAnotherRequest());
		tfUMarriage.setCreateTime(new Date());
		tfUMarriage.setHeight(savePersonRequest.getHeight());
		tfUMarriage.setEducationLevel(savePersonRequest.getEducationLevel());
		tfUMarriage.setIsDeleted(IsDeletedConstants.IN_USE);
		tfUMarriage.setWeight(savePersonRequest.getWeight());
		tfUMarriage.setProvinceCode(savePersonRequest.getProvinceCode());
		tfUMarriage.setSchool(savePersonRequest.getSchool());
		tfUMarriage.setEparchyCode(savePersonRequest.getEparchyCode());
		tfUMarriage.setWeixin(savePersonRequest.getWeixin());
		tfUMarriage.setRemark(savePersonRequest.getRemark());
		tfUMarriage.setSex(savePersonRequest.getSex());
		tfUMarriage.setDegree(savePersonRequest.getDegree());
		tfUMarriage.setWork(savePersonRequest.getWork());
		tfUMarriage.setPicId(savePersonRequest.getPicId());
		tfUMarriage.setIp(request.getRemoteHost());
		tfUMarriageMapper.insert(tfUMarriage);
	}

	public boolean checkData(HttpServletRequest request, SavePersonRequest savePersonRequest) throws Exception {
		// 校验性别
		if (!StringUtils.isNotEmpty(savePersonRequest.getSex())) {
			throw new Exception("请选择性别");
		}
		if (!StringUtils.isNotEmpty(savePersonRequest.getWeixin())) {
			throw new Exception("请输入微信");
		}
		// 校验名称
		if (!StringUtils.isNotEmpty(savePersonRequest.getUserName())) {
			throw new Exception("请输入姓名");

		}
		if (savePersonRequest.getUserName().length() > 100) {
			throw new Exception("姓名太长");
		}
		// 校验省份地市关系
		if (savePersonRequest.getProvinceCode() != null && savePersonRequest.getEparchyCode() != null) {
			TdCityExample tdCityExample = new TdCityExample();
			tdCityExample.or().andCidEqualTo(savePersonRequest.getEparchyCode())
					.andPidEqualTo(savePersonRequest.getProvinceCode());
			long count = tdCityMapper.countByExample(tdCityExample);
			if (count == 0) {
				throw new Exception("地市不归属改省份");
			}
		}
		// 校验ip
		TfUMarriageExample example = new TfUMarriageExample();
		SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date todayDate = sdfDateFormat.parse(sdfDateFormat.format(new Date()));
		example.or().andIpEqualTo(request.getRemoteHost()).andIsDeletedEqualTo(IsDeletedConstants.IN_USE)
				.andCreateTimeGreaterThan(todayDate);

		long num = tfUMarriageMapper.countByExample(example);
		if (num > 3) {
			throw new Exception("当前ip的当日注册已超过上限(3)");
		}
		return true;
	}

	@Override
	public void checkFile(MultipartFile file) throws Exception {
		// TODO Auto-generated method stub
		// 判断上传的文件是否为空
		boolean isEmpty = file.isEmpty();
		logger.info("\t isEmpty=" + isEmpty);
		if (isEmpty) {
			throw new Exception("上传失败！上传的文件为空！");
		}

		// 检查文件大小
		long fileSize = file.getSize();
		logger.info("\t size=" + fileSize);
		if (fileSize > 5 * 1024 * 1024) {
			throw new Exception("上传失败！上传的文件大小超出了限制！");
		}

		// 检查文件MIME类型
		String contentType = file.getContentType();
		logger.info("\t contentType=" + contentType);
	}

	@Override
	public void checkDir(String parentDir) throws Exception {
		// TODO Auto-generated method stub
		File parent = new File(parentDir);
		if (!parent.exists()) {
			parent.mkdirs();
		}
		File parent2 = new File(parentDir + "/marriage");
		if (!parent2.exists()) {
			parent2.mkdirs();
		}
	}

	@Override
	public void savePicture(String fileId, String fileName, long size, String suffix) {
		// TODO Auto-generated method stub
		TdFile tdFile = new TdFile();
		tdFile.setFileId(fileId);
		tdFile.setFileName(fileName);
		tdFile.setCreateStaffId("temp");
		tdFile.setCreateTime(new Date());
		tdFile.setFileSuffix(suffix);
		tdFile.setFileSize(size);
		tdFile.setFileType("01");
		tdFileMapper.insert(tdFile);
	}

	@Override
	public void deletePerson(HttpServletRequest request, DeletePersonRequest deletePersonRequest) throws Exception {
		// TODO Auto-generated method stub
		checkIpDelete(request, deletePersonRequest);
		TfUMarriage tfUMarriage = new TfUMarriage();
		tfUMarriage.setIsDeleted(IsDeletedConstants.DELETED);
		tfUMarriage.setUpdateTime(new Date());
		tfUMarriage.setId(deletePersonRequest.getId());
		tfUMarriageMapper.updateByPrimaryKeySelective(tfUMarriage);
	}

	public void checkIpDelete(HttpServletRequest request, DeletePersonRequest deletePersonRequest) throws Exception {
		// TODO Auto-generated method stub
		TfUMarriage tfUMarriage = tfUMarriageMapper.selectByPrimaryKey(deletePersonRequest.getId());
		if (tfUMarriage == null) {
			throw new Exception("用户 不存在");
		} else {
			if (!tfUMarriage.getIp().equals(request.getRemoteAddr())) {
				throw new Exception("创建用户ip和删除用户ip不一致，请联系管理员删除");
			}
		}
	}


}
